package com.example.gss.controller;

import com.example.gss.entity.ScholarshipApplication;
import com.example.gss.Service.ScholarshipApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/scholarship-applications")
public class ScholarshipApplicationController {

    @Autowired
    private ScholarshipApplicationService scholarshipApplicationService;

    /**
     * 创建奖学金申请
     */
    @PostMapping
    public ResponseEntity<?> createApplication(@RequestBody ScholarshipApplication application) {
        try {
            // 检查是否已存在申请
            if (scholarshipApplicationService.hasExistingApplication(application.getStudentId(), application.getScholarshipId())) {
                return new ResponseEntity<>("您已经申请过该奖学金，不能重复申请", HttpStatus.CONFLICT);
            }
            
            // 生成申请ID
            application.setApplicationId(UUID.randomUUID().toString());
            // 设置申请日期
            application.setApplyDate(new Date());
            // 设置默认状态为申请中
            application.setStatus("申请中");
            // 设置默认分数为0
            application.setTotalScore(new java.math.BigDecimal("0"));
            application.setIdeologyScore(new java.math.BigDecimal("0"));
            application.setAcademicScore(new java.math.BigDecimal("0"));
            application.setResearchScore(new java.math.BigDecimal("0"));
            application.setServiceScore(new java.math.BigDecimal("0"));
            
        ScholarshipApplication createdApplication = scholarshipApplicationService.createApplication(application);
        return new ResponseEntity<>(createdApplication, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>("申请提交失败: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 创建或更新奖学金申请（如果已存在则覆盖）
     */
    @PostMapping("/create-or-update")
    public ResponseEntity<?> createOrUpdateApplication(@RequestBody ScholarshipApplication application) {
        try {
            ScholarshipApplication result = scholarshipApplicationService.createOrUpdateApplication(application);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("申请提交失败: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 获取所有奖学金申请
     */
    @GetMapping
    public ResponseEntity<List<ScholarshipApplication>> getAllApplications(@RequestParam(required = false) String status) {
        List<ScholarshipApplication> applications;
        if (status != null && !status.isEmpty()) {
            applications = scholarshipApplicationService.findApplicationsByStatus(status);
        } else {
            applications = scholarshipApplicationService.getAllApplications();
        }
        return new ResponseEntity<>(applications, HttpStatus.OK);
    }

    /**
     * 根据学生ID查询奖学金申请
     */
    @GetMapping("/search/student")
    public ResponseEntity<List<ScholarshipApplication>> findApplicationsByStudentId(@RequestParam String studentId) {
        List<ScholarshipApplication> applications = scholarshipApplicationService.findApplicationsByStudentId(studentId);
        return new ResponseEntity<>(applications, HttpStatus.OK);
    }

    /**
     * 根据学生ID和状态查询奖学金申请
     */
    @GetMapping("/search/student/status")
    public ResponseEntity<List<ScholarshipApplication>> findApplicationsByStudentIdAndStatus(
            @RequestParam String studentId, 
            @RequestParam(required = false) String status) {
        List<ScholarshipApplication> applications;
        if (status != null && !status.isEmpty()) {
            // 先根据状态查询，再筛选学生ID
            List<ScholarshipApplication> statusApplications = scholarshipApplicationService.findApplicationsByStatus(status);
            applications = statusApplications.stream()
                    .filter(app -> studentId.equals(app.getStudentId()))
                    .toList();
        } else {
            // 只根据学生ID查询
            applications = scholarshipApplicationService.findApplicationsByStudentId(studentId);
        }
        return new ResponseEntity<>(applications, HttpStatus.OK);
    }

    /**
     * 根据ID获取奖学金申请
     */
    @GetMapping("/{applicationId}")
    public ResponseEntity<ScholarshipApplication> getApplicationById(@PathVariable String applicationId) {
        Optional<ScholarshipApplication> applicationOptional = scholarshipApplicationService.getApplicationById(applicationId);
        return applicationOptional.map(application -> new ResponseEntity<>(application, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 更新奖学金申请
     */
    @PutMapping("/{applicationId}")
    public ResponseEntity<ScholarshipApplication> updateApplication(@PathVariable String applicationId, @RequestBody ScholarshipApplication application) {
        application.setApplicationId(applicationId);
        ScholarshipApplication updatedApplication = scholarshipApplicationService.updateApplication(application);
        return new ResponseEntity<>(updatedApplication, HttpStatus.OK);
    }

    /**
     * 审核通过申请
     */
    @PutMapping("/{applicationId}/approve")
    public ResponseEntity<?> approveApplication(@PathVariable String applicationId) {
        try {
            Optional<ScholarshipApplication> applicationOptional = scholarshipApplicationService.getApplicationById(applicationId);
            if (applicationOptional.isPresent()) {
                ScholarshipApplication application = applicationOptional.get();
                application.setStatus("已通过");
                scholarshipApplicationService.updateApplication(application);
                return new ResponseEntity<>("申请已通过", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("申请不存在", HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>("审核失败: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 审核拒绝申请
     */
    @PutMapping("/{applicationId}/reject")
    public ResponseEntity<?> rejectApplication(@PathVariable String applicationId) {
        try {
            Optional<ScholarshipApplication> applicationOptional = scholarshipApplicationService.getApplicationById(applicationId);
            if (applicationOptional.isPresent()) {
                ScholarshipApplication application = applicationOptional.get();
                application.setStatus("已拒绝");
                scholarshipApplicationService.updateApplication(application);
                return new ResponseEntity<>("申请已拒绝", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("申请不存在", HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>("审核失败: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 删除奖学金申请
     */
    @DeleteMapping("/{applicationId}")
    public ResponseEntity<Void> deleteApplication(@PathVariable String applicationId) {
        scholarshipApplicationService.deleteApplication(applicationId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 根据奖学金ID查询申请
     */
    @GetMapping("/search/scholarship")
    public ResponseEntity<List<ScholarshipApplication>> findApplicationsByScholarshipId(@RequestParam String scholarshipId) {
        List<ScholarshipApplication> applications = scholarshipApplicationService.findApplicationsByScholarshipId(scholarshipId);
        return new ResponseEntity<>(applications, HttpStatus.OK);
    }

    /**
     * 根据状态查询申请
     */
    @GetMapping("/search/status")
    public ResponseEntity<List<ScholarshipApplication>> findApplicationsByStatus(@RequestParam String status) {
        List<ScholarshipApplication> applications = scholarshipApplicationService.findApplicationsByStatus(status);
        return new ResponseEntity<>(applications, HttpStatus.OK);
    }

    /**
     * 获取申请统计数据
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getApplicationStats() {
        try {
            List<ScholarshipApplication> allApplications = scholarshipApplicationService.getAllApplications();
            
            long pendingCount = allApplications.stream()
                    .filter(app -> "pending".equals(app.getStatus()) || "申请中".equals(app.getStatus()))
                    .count();
            long approvedCount = allApplications.stream()
                    .filter(app -> "approved".equals(app.getStatus()) || "已通过".equals(app.getStatus()))
                    .count();
            long rejectedCount = allApplications.stream()
                    .filter(app -> "rejected".equals(app.getStatus()) || "已拒绝".equals(app.getStatus()))
                    .count();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("pendingCount", pendingCount);
            stats.put("approvedCount", approvedCount);
            stats.put("rejectedCount", rejectedCount);
            
            return new ResponseEntity<>(stats, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取最近申请
     */
    @GetMapping("/recent")
    public ResponseEntity<List<ScholarshipApplication>> getRecentApplications() {
        try {
            List<ScholarshipApplication> allApplications = scholarshipApplicationService.getAllApplications();
            // 按申请时间倒序排列，取前10条
            List<ScholarshipApplication> recentApplications = allApplications.stream()
                    .sorted((a, b) -> b.getApplyDate().compareTo(a.getApplyDate()))
                    .limit(10)
                    .toList();
            return new ResponseEntity<>(recentApplications, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 重新计算申请总分
     */
    @PutMapping("/{applicationId}/recalculate-score")
    public ResponseEntity<?> recalculateTotalScore(@PathVariable String applicationId) {
        try {
            ScholarshipApplication updatedApplication = scholarshipApplicationService.recalculateTotalScore(applicationId);
            if (updatedApplication != null) {
                return new ResponseEntity<>(updatedApplication, HttpStatus.OK);
            } else {
                return new ResponseEntity<>("申请不存在", HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>("重新计算失败: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 获取奖学金排名
     */
    @GetMapping("/scoreboard/{scholarshipId}")
    public ResponseEntity<List<ScholarshipApplication>> getScoreboard(@PathVariable String scholarshipId) {
        try {
            List<ScholarshipApplication> scoreboard = scholarshipApplicationService.findApplicationsByScholarshipId(scholarshipId);
            return new ResponseEntity<>(scoreboard, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}